<template>
    <el-container>
        <el-header style="padding: 0; height: auto;margin-top: 15px;">
            <div style=" padding-left: 10px;">
                <el-row :gutter="50" style="width: 100%;overflow-y:hidden" >
                    <el-col :span="1">
                        <el-checkbox
                            v-model="checked"
                            style="padding-top: 14px; padding-left: 2px"
                        >
                        </el-checkbox>
                    </el-col>

                    <el-col :span="7" style="margin-left:0px">
                        <el-input placeholder="请输入接口名称" clearable v-model.trim="search"  @keyup.enter.native="getAPIList">
                            <el-button slot="append" icon="el-icon-search" @click="getAPIList"></el-button>
                        </el-input>
                    </el-col>

                    <!-- <el-col :span="7" style="margin-left: -10px">
                        <el-pagination
                            style="margin-top: 5px;"
                            :page-size="12"
                            background
                            @current-change="handleCurrentChange"
                            :current-page.sync="currentPage"
                            layout="total, prev, pager, next, jumper"
                            :total="apiData.count"
                        >
                        </el-pagination>
                    </el-col> -->

                </el-row>
            </div>
        </el-header>

        <el-container>
            <el-main style="padding: 0; margin-left: 10px">
                <el-dialog
                    title="批量添加接口"
                    :visible.sync="dialogTreeVisible"
                    width="40%"
                >
                    <div>
                        <div>
                            <span>请选择一个节点</span>
                        </div>
                        <div style="margin-top: 20px">
                            <el-input
                                placeholder="输入节点名称进行过滤"
                                v-model="filterText"
                                size="medium"
                                clearable
                                prefix-icon="el-icon-search"
                            >
                            </el-input>

                            <el-tree
                                :filter-node-method="filterNode"
                                :data="dataTree"
                                show-checkbox
                                node-key="id"
                                :expand-on-click-node="false"
                                check-on-click-node
                                @check-change="handleClick"
                                :check-strictly="true"
                                :highlight-current="true"
                                ref="tree"
                            >
                            <span class="custom-tree-node"
                                  slot-scope="{ node, data }"
                            >
                                <span><i class="iconfont" v-html="expand"></i>&nbsp;&nbsp;{{ node.label }}</span>
                            </span>
                            </el-tree>
                        </div>

                    </div>
                    <span slot="footer" class="dialog-footer">
                    <el-button size="small" @click="dialogTreeVisible = false">取 消</el-button>
                    <el-button size="small" type="primary" @click="addAPIList">确 定</el-button>


                  </span>
                </el-dialog>


                <div style="position: fixed; bottom: 0; right:0; left: 460px; top: 26%; height: 100%;" v-show="apiData.count !== 0 ">
                    <el-table
                        v-loading="loading"
                        element-loading-text="正在玩命加载"
                        highlight-current-row
                        ref="multipleTable"
                        :data="apiData.results"
                        height="550"
                        :show-header="false"
                        :cell-style="{paddingTop: '4px', paddingBottom: '4px'}"
                        @cell-mouse-enter="cellMouseEnter"
                        @cell-mouse-leave="cellMouseLeave"
                        style="width: 100%;padding-bottom: 16%;"
                        @selection-change="handleSelectionChange"
                    >
                        <el-table-column
                            type="selection"
                            width="50"
                        >
                        </el-table-column>

                        <el-table-column
                            align="center"
                        >
                            <template slot-scope="scope">
                                <div class="block block_post" v-if="scope.row.method.toUpperCase() === 'POST' ">
                                    <span class="block-method block_method_post block_method_color">POST</span>
                                    <span class="block-method block_url">{{scope.row.url}}</span>
                                    <span class="block-summary-description">{{scope.row.name}}</span>
                                </div>

                                <div class="block block_get" v-if="scope.row.method.toUpperCase() === 'GET' ">
                                    <span class="block-method block_method_get block_method_color">GET</span>
                                    <span class="block-method block_url">{{scope.row.url}}</span>
                                    <span class="block-summary-description">{{scope.row.name}}</span>
                                </div>

                                <div class="block block_put" v-if="scope.row.method.toUpperCase() === 'PUT' ">
                                    <span class="block-method block_method_put block_method_color">PUT</span>
                                    <span class="block-method block_url">{{scope.row.url}}</span>
                                    <span class="block-summary-description">{{scope.row.name}}</span>
                                </div>

                                <div class="block block_delete" v-if="scope.row.method.toUpperCase() === 'DELETE' ">
                                    <span class="block-method block_method_delete block_method_color">DELETE</span>
                                    <span class="block-method block_url">{{scope.row.url}}</span>
                                    <span class="block-summary-description">{{scope.row.name}}</span>
                                </div>

                                <div class="block block_patch" v-if="scope.row.method.toUpperCase() === 'PATCH' ">
                                    <span class="block-method block_method_patch block_method_color">PATCH</span>
                                    <span class="block-method block_url">{{scope.row.url}}</span>
                                    <span class="block-summary-description">{{scope.row.name}}</span>
                                </div>

                                <div class="block block_head" v-if="scope.row.method.toUpperCase() === 'HEAD' ">
                                    <span class="block-method block_method_head block_method_color">HEAD</span>
                                    <span class="block-method block_url">{{scope.row.url}}</span>
                                    <span class="block-summary-description">{{scope.row.name}}</span>
                                </div>

                                <div class="block block_options" v-if="scope.row.method.toUpperCase()=== 'OPTIONS' ">
                                    <span class="block-method block_method_options block_method_color">OPTIONS</span>
                                    <span class="block-method block_url">{{scope.row.url}}</span>
                                    <span class="block-summary-description">{{scope.row.name}}</span>
                                </div>

                            </template>
                        </el-table-column>

                        <el-table-column
                            width="200"
                        >
                            <template slot-scope="scope">
                                <el-row v-show="currentRow === scope.row">
                                    <!-- <el-button
                                        type="info"
                                        icon="el-icon-edit"
                                        circle size="mini"
                                        @click="handleRowClick(scope.row)"
                                        title="编辑"
                                    ></el-button> -->
                                    <el-button
                                        type="danger"
                                        icon="el-icon-delete"
                                        circle size="mini"
                                        @click="handleDelApi(scope.row.id)"
                                        title="删除"
                                    ></el-button>
                                </el-row>
                            </template>
                        </el-table-column>

                    </el-table>
                </div>

            </el-main>
        </el-container>
    </el-container>
</template>

<script>

    export default {
        components: {
        },
        name: "ChromeApiList",
        props: {
            run: Boolean,
            back: Boolean,
            node: {
                require: true
            },
            project: {
                require: true
            },
            del: Boolean
        },
        data() {
            return {
                checked:false,
                search: '',
                asyncs: false,
                filterText: '',
                loading: true,
                expand: '&#xe65f;',
                dataTree: {},
                dialogTreeVisible: false,
                dialogTableVisible: false,
                summary: {},
                selectAPI: [],
                currentRow: '',
                currentPage: 1,
                apiData: {
                    count: 0,
                    results: []
                },
                dataTypeOptions: [{
                    label: 'String',
                    value: 1
                }, {
                    label: 'Integer',
                    value: 2
                }, {
                    label: 'Float',
                    value: 3
                }, {
                    label: 'Boolean',
                    value: 4
                }, {
                    label: 'File',
                    value: 5
                }],
                dataOptions: [{
                    label: 'forms',
                    value: 'forms',
                }, {
                    label: 'json',
                    value: 'json',
                }, {
                    label: 'params',
                    value: 'params'
                }],
                dataType: 'forms',
            }
        },
        watch: {
            filterText(val) {
                this.$refs.tree.filter(val);
            },

            run() {

                this.asyncs = false;
                if(this.selectAPI.length<1){
                    this.$notify.error("至少选择一个接口添加")
                    return
                }
                //如果左边已选择了node-tree就直接调用保存接口函数，否则调用dilago弹出tree选择
                if(this.node!=""){
                    this.addAPIList()
                }
                else{
                    this.getTree();
                }

            },
            back() {
                this.getAPIList();
            },
            checked() {
                if (this.checked) {
                    this.toggleAll();
                } else {
                    this.toggleClear();
                }
            },

            del() {
                if (this.selectAPI.length !== 0) {
                    this.$confirm('此操作将永久删除API，是否继续?', '提示', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning',
                    }).then(() => {
                        this.$api.delAllAPI({data: this.selectAPI}).then(resp => {
                            this.getAPIList();
                        })
                    })
                } else {
                    this.$notify.warning({
                        message: '请至少选择一个接口'
                    })
                }
            }
        },

        methods: {
            filterNode(value, data) {
                if (!value) return true;
                return data.label.indexOf(value) !== -1;
            },
            handleClick(data,checked, node){
                        if(checked){
                            this.$refs.tree.setCheckedNodes([data]);
                        }
                    },


            addAPIList() {
                //判断node是通过弹框选择的还是左边tree选择的
                var node;
                if (this.node!=""){
                    node=this.node
                }else{
                     const relation = this.$refs.tree.getCheckedKeys();
                    if (relation.length<1){
                        this.$notify.warning("至少选择一个节点")
                        return
                    }
                    node=relation[0];
                }
                // return
                // console.log(this.selectAPI)
                const uploadLoading=this.$loading({
                        "text":"正在批量导入....","background":
                        "rgba(0, 0, 0, 0.8)"})

                this.selectAPI.forEach((item,index,data) => {
                    console.log("index"+index+"item:"+JSON.stringify(item))
                    //先对request里面的参数进行一次数据检验解析转换
                    let request={files:{"files":{},"desc":{}},"form":this.parseForm(this.loaderRequest(item.body.request.data)),"json":this.parseJson(item.body.request.json_data),"params":this.parseParams(item.body.request.params)}
                    this.$api.addAPI({
                        header:this.parseHeader(item.body.header),
                        request: request,
                        extract:{"extract":[],"desc":{}},
                        validate: {"validate":[]},
                        variables: this.parseVariables(this.loaderVariables(item.body.variables)),
                        hooks:{"setup_hooks":[],"teardown_hooks":[]},
                        url: item.url,
                        method: item.method,
                        name: item.name,
                        times: 1,
                        nodeId: node,
                        project:this.project
                    }).then(resp => {
                        if (resp.success) {
                            this.$notify.success(resp.msg);
                            //添加成功的api从列表移除
                            this.apiData.results.splice(this.apiData.results.indexOf(item),1);
                        } else {
                            this.$notify.error(resp.msg)
                        }
                    })
                });
                this.dialogTreeVisible=false;
                uploadLoading.close();
            },
            getTree() {
                console.log("id",)
                this.$api.getTree(this.project, {params: {type: 1}}).then(resp => {
                    this.dataTree = resp.tree;
                    this.dialogTreeVisible = true;
                })
            },

            handleSelectionChange(val) {
                this.selectAPI = val;
            },

            toggleAll() {
                this.$refs.multipleTable.toggleAllSelection();
            },

            toggleClear() {
                this.$refs.multipleTable.clearSelection();
            },

            getAPIList() {
               this.$api.getApiList(this.$route.query.datakey).then(res=>{
                    this.apiData = res;

                })
                this.loading = false;

            },
            handleCurrentChange(val) {
                this.$api.getPaginationBypage({
                    params: {
                        page: this.currentPage,
                        node: this.node,
                        project: this.project,
                        search: this.search
                    }
                }).then(res => {
                    this.apiData = res;
                })
            },

            //删除api
            handleDelApi(index) {
                this.$confirm('确定删除该API，是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning',
                }).then(() => {
                    this.apiData.results.splice(index,1)
                })
            },

            // 编辑API
            // handleRowClick(row) {
            //     this.$api.getAPISingle(row.id).then(resp => {
            //         if (resp.success) {
            //             this.$emit('api', resp);
            //         } else {
            //             this.$notify.error(resp.msg)
            //         }
            //     })
            // },


            cellMouseEnter(row) {
                this.currentRow = row;
            },

            cellMouseLeave(row) {
                this.currentRow = '';
            },

             parseHeader(tableData) {
                let header = {
                    header: {},
                    desc: {}
                };
                for (let content of tableData) {
                    if (content['key'] !== '' && content['value'] !== '') {
                        header.header[content['key']] = content['value'];
                        header.desc[content['key']] = content['desc'];
                    }
                }
                return header;
            },
            parseFile() {
                let files = {
                    files: {},
                    desc: {}
                };

                for (let content of this.formData) {
                    // 是文件
                    if (content['key'] !== '' && content['type'] === 5) {
                        files.files[content['key']] = content['value'];
                        files.desc[content['key']] = content['desc'];
                    }
                }
                return files
            },

            // 表单格式化
            parseForm(formData) {
                let form = {
                    data: {},
                    desc: {}
                };
                for (let content of formData) {
                    // file 不处理
                    if (content['key'] !== '' && content['type'] !== 5) {
                        const value = this.parseType(content['type'], content['value']);

                        if (value === 'exception') {
                            continue;
                        }

                        form.data[content['key']] = value;
                        form.desc[content['key']] = content['desc'];
                    }
                }
                return form;
            },

            parseParams(paramsData) {
                let params = {
                    params: {},
                    desc: {}
                };
                for (let content of paramsData) {
                    if (content['key'] !== '') {
                        params.params[content['key']] = content['value'];
                        params.desc[content['key']] = content['desc'];
                    }
                }
                return params;
            },

            parseJson(jsonData) {
                let json = {};
                if ( jsonData !== '') {
                    try {
                        json = JSON.parse(jsonData);
                    }
                    catch (err) {
                        this.$notify.error('json数据格式错误');
                    }
                }
                return json;
            },

            // 类型转换
            parseType(type, value) {
                let tempValue;
                const msg = String(value) + ' => ' + this.dataTypeOptions[type - 1].label + ' 转换异常, 该数据自动剔除';
                switch (type) {
                    case 1:
                        if (String(value).toLowerCase() === 'null' || String(value).toLowerCase() === 'none') {
                            tempValue = null;
                        } else {
                            tempValue = String(value);
                        }
                        break;
                    case 2:
                        tempValue = parseInt(value);
                        break;
                    case 3:
                        tempValue = parseFloat(value);
                        break;
                    case 4:
                        tempValue = value === 'true';
                        break;
                }

                if (tempValue !== 0 && !tempValue && type !== 4 && type !== 1) {
                    this.$notify.error(msg);
                    return 'exception'
                }

                return tempValue;
            },

            loaderRequest(response) {
                let obj = [];
                for (let content of response) {
                    if (content['type'] === 4) {
                        if (content['value'] === true) {
                            content['value'] = 'true'
                        } else {
                            content['value'] = 'false'
                        }
                    }
                    obj.push(content)
                }
                return obj
            },



            parseVariablesType(type, value) {
                let tempValue;
                const msg = value + ' => ' + this.dataTypeOptions[type - 1].label + ' 转换异常, 该数据自动剔除';
                switch (type) {
                    case 1:
                        if (String(value).toLowerCase() === 'null' || String(value).toLowerCase() === 'none'){
                            tempValue = null;
                        }else {
                            tempValue = String(value);
                        }
                        break;
                    case 2:
                        tempValue = parseInt(value);
                        break;
                    case 3:
                        tempValue = parseFloat(value);
                        break;
                    case 4:
                        tempValue = value === 'true';
                        break;
                    case 5:
                        try {
                            tempValue = JSON.parse(value);
                        }
                        catch (err) {
                            tempValue = false
                        }
                        break;
                    case 6:
                        try {
                            tempValue = JSON.parse(value);
                        }
                        catch (err) {
                            tempValue = false
                        }
                        break;
                }

                if (tempValue !== 0 && !tempValue && type !== 4 && type !== 1) {
                    this.$notify.error(msg);
                    return 'exception'
                }
                return tempValue;
            },
            //变量格式化variables
            parseVariables(tableData) {
                let variables = {
                    variables: [],
                    desc: {}
                };
                for (let content of tableData) {
                    if (content['key'] !== '') {
                        let obj = {};
                        const value = this.parseVariablesType(content['type'], content['value']);
                        if (value === 'exception') {
                            continue;
                        }
                        obj[content['key']] = value;
                        variables.variables.push(obj);
                        variables.desc[content['key']] = content['desc'];
                    }
                }
                return variables;
            },
            loaderVariables(response){
                let obj = [];
                for (let content of response) {
                    if (content['type'] === 4) {
                        if (content['value'] === true){
                            content['value'] = 'true'
                        }else{
                            content['value'] = 'false'
                        }
                    }
                    obj.push(content)
                }
                return obj
            },
        },
        mounted() {
            this.getAPIList();
        }
    }
</script>

<style scoped>


</style>
